<?php
class RecipesController extends AppController {
	public $helpers = array('Html', 'Form');
	public $uses = array('Recipe', 'User','Comment');


	public function beforeFilter() {
        $this->Auth->allow(array('viewByTime','viewByComments','viewByStars','view','details','index','search'));
    }
	public function index(){
		$this->redirect(array('action' => 'view'));
	}
	
	public function view(){
    	$this->paginate = array(
        	    'limit' => 20
    	);
		
    	$newUsers = $this->User->find('all',array('limit'=>7,'order'=>array('id'=>'desc')));
		$this->set('newUsers',$newUsers);
		$data = $this->paginate('Recipe');                  
        $this->set('posts',$data);
	}


	public function viewByTime(){
    	$this->paginate = array(
        	    'limit' => 20,
            	'order' => array('Recipe.createdTime' => 'desc'),
    	);

    	$newUsers = $this->User->find('all',array('limit'=>7,'order'=>array('id'=>'desc')));
		$this->set('newUsers',$newUsers);

		$data = $this->paginate('Recipe');                  
        $this->set('posts',$data);
	
	}
	
	public function viewByComments(){
    	$this->paginate = array(
        	    'limit' => 20,
            	'order' => array('Recipe.commentsNumber' => 'desc'),
    	);

    	$newUsers = $this->User->find('all',array('limit'=>7,'order'=>array('id'=>'desc')));
		$this->set('newUsers',$newUsers);

		$data = $this->paginate('Recipe');                  
        $this->set('posts',$data);
	}
	
	public function viewByStars(){
    	$this->paginate = array(
        	    'limit' => 20,
            	'order' => array('Recipe.currentScore' => 'desc'),
    	);

    	$newUsers = $this->User->find('all',array('limit'=>7,'order'=>array('id'=>'desc')));
		$this->set('newUsers',$newUsers);
		
		$data = $this->paginate('Recipe');                  
        $this->set('posts',$data);
	}
	
	
	public function add(){
        if ($this->request->is('post')) {
            $this->Recipe->create();
			$this->request->data['Recipe']['userId'] = $this->Session->read('userid');
			$this->request->data['Recipe']['createdTime'] = date('Y-m-d H:i:s');
            if ($this->Recipe->save($this->request->data)) {
                $this->Session->setFlash('您的菜谱储存成功.');
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash('菜谱储存失败');
            }
        }
	}
	
	public function delete($id=null){
        if (!$id) {
            throw new NotFoundException(__('Invalid post'));
        }
		$recipe    = $this->Recipe->findById($id);
		$userId    = $this->Session->read('userid');
		$userGroup = $this->Session->read('usergroup');
		if(($userId == $recipe['Recipe']['userId'])||($userGroup == 1)){
			$this->Recipe->delete($id);
			$this->Comment->deleteAll(array('recipeId'=>$id));
			$this->Session->setFlash(__('删除成功'));
		}
		else{
			$this->Session->setFlash(__('删除失败'));
		}
       $this->redirect($this->referer());
	}
	
	public function modify($id=null){
        if (!$id) {
            throw new NotFoundException(__('Invalid post'));
        }
	}
	
	public function details($recipeId=null){
        if (!$recipeId) {
            throw new NotFoundException(__('Invalid post'));
        }
		
		$this->set('recipe',$this->Recipe->findById($recipeId));
		$this->set('comments', $this->Comment->find('all', array(
			'conditions' => array(
				'recipeId' => $recipeId
					)
				)
			)
		);

	}

	public function search(){

    	$newUsers = $this->User->find('all',array('limit'=>7,'order'=>array('id'=>'desc')));
		$this->set('newUsers',$newUsers);

		$field = $this->params['url']['field'];
		$query = $this->params['url']['query'];
		$order = $this->params['url']['order'];
		
		if($field==""){
			$field = 'name';
		}
		if($order==""){
			$order = 'createdTime';
		}


		if($field == 'ingredient'){

		$this->paginate = array(
        	    'limit' => 20,
				'conditions' => array(
							"or" =>
								array
								(
								"ingredient0 like" => '%'.$query.'%',
								"ingredient1 like" => '%'.$query.'%',
								"ingredient2 like" => '%'.$query.'%',
								)
						),
				'recursive' => 0,
				'order' => array($order => 'desc')
    	);

		$data = $this->paginate('Recipe');
		$this->set('posts',$data);
		}
		else{
			$this->paginate = array(
	        	    'limit' => 20,
					'conditions' => array(
								"or" =>
									array
									(
									//$field." like" => $query,
									//$field." like" => $query.'%',
									$field." like" => '%'.$query.'%',
									//$field." like" => '%'.$query,
									)
							),
					'recursive' => 0,
					'order' => array($order => 'desc')
	    	);
			$data = $this->paginate('Recipe');
			$this->set('posts',$data);
		}


	}

	
	public function comment(){
		if ($this->request->is('post')) {
			$this->Comment->create();
			$this->request->data['Comment']['userId'] = $this->Session->read('userid');
			//if (!isset($_SESSION['userid'])) $this->redirect(array('controller'=>'users','action' => 'login'));
			$this->request->data['Comment']['createdTime'] = date('Y-m-d H:i:s');
            if ($this->Comment->save($this->request->data)) {
            	$this->Recipe->query("update recipe set commentsNumber = commentsNumber+1 where id={$this->request->data['Comment']['recipeId']}");
                $this->Session->setFlash(__('评论成功'));
            } else {
                $this->Session->setFlash(__('评论失败，请重试'));
            }

           $this->redirect(array('action' => 'details', $this->request->data['Comment']['recipeId']));
        }
	}

	public function delComment($id,$recipeId){

		$userGroup = $this->Session->read('usergroup');
		if ($userGroup == 1){
			$this->Comment->delete($id);
			$this->Recipe->query("update recipe set commentsNumber = commentsNumber-1 where id={$recipeId}");
			$this->Session->setFlash(__('删除成功'));	
		}else{
			$this->Session->setFlash(__('您没有权限'));
		}

		$this->redirect($this->referer());
	
	}

	public function evalue($recipeId){
		$this->layout = 'ajax';
		$score        = $this->request->data['score'];
		$this->Recipe->query("update recipe set totalStars=totalStars+{$score}, markNumber=markNumber+1, currentScore = totalStars / markNumber where id = {$recipeId}");
		$data         = $this->Recipe->query("SELECT `currentScore` from recipe WHERE id = {$recipeId}");
		$this->set('data',$data);
	}
	
}



?>
	
